package com.quectel.cms.controller.partyeducationtraining;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.training.ChangePublishStatusVo;
import com.quectel.constant.core.partyeducationtraining.TrainingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingPersonDto;
import com.quectel.core.module.partyeducationtraining.dto.ref.TrainingItemRefPersonDto;
import com.quectel.core.module.partyeducationtraining.dto.ref.TrainingRefPersonDto;
import com.quectel.core.module.partyeducationtraining.service.TrainingPersonService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:39
 */
@RestController
@RequestMapping("training")
@Tag(name = "TrainingController", description = "培训表相关api")
public class TrainingController extends BaseController {

    @DubboReference
    private TrainingService trainingService;
    @DubboReference
    private TrainingPersonService trainingPersonService;
    @DubboReference
    private PartyPersonService partyPersonService;

    @PostMapping("changePublishStatus")
    @RequirePermissions(values = "training:edit")
    public Response<Object> changePublishStatus(@RequestBody ChangePublishStatusVo changePublishStatusVo) {
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(changePublishStatusVo.getTrainingId()));
        if (trainingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        if (!TrainingConstants.PublishStatusEnum.ON.getPublishStatus().equals(changePublishStatusVo.getPublishStatus())
                && !TrainingConstants.PublishStatusEnum.OFF.getPublishStatus().equals(changePublishStatusVo.getPublishStatus())) {
            return Response.error("错误的发布状态");
        }

        TrainingDto newlyDto = new TrainingDto();
        newlyDto.setId(changePublishStatusVo.getTrainingId());
        newlyDto.setPublishStatus(changePublishStatusVo.getPublishStatus());
        super.fillEditCommonData(newlyDto);
        trainingService.updateById(newlyDto);
        return Response.ok();
    }


    /**
     * 导出课时学习进度列表
     */
    @GetMapping("exportPersonExcel")
    @RequirePermissions(values = "training:export")
    @Operation(summary = "导出课程学习列表")
    public void exportPersonExcel(@RequestParam Map<String, Object> params,
                                  HttpServletResponse resp) {
        //查询列表数据
        Request request = Request.configParamsNotPage(params)
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getName))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getMobile));

        super.fillAuthorityData(params);
        List<TrainingRefPersonDto> list = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 10000);
        while (true) {
            params.put("offset", pageNo++ * 10000);
            List<TrainingRefPersonDto> trainingCommentDtos = trainingPersonService.queryPersonList(params);
            if (CollectionUtils.isEmpty(trainingCommentDtos)) {
                break;
            }
            list.addAll(trainingCommentDtos);

        }
        String[] headers = new String[]{"课时名称", "姓名", "联系电话", "所属部门", "进度", "开始时间", "完成时间", "状态"};
        List<String[]> dataList = new ArrayList<>();
        for (TrainingRefPersonDto data : list) {
            String status = "学习中";
            if (data.getEndTime() != null) {
                status = "已结束";
            }
            if (data.getStartTime() == null) {
                status = "未开始";
            }

            String[] item = new String[headers.length];
            item[0] = data.getTrainingName();
            item[1] = data.getName();
            item[2] = data.getMobile();
            item[3] = data.getParty() == null ? "" : data.getParty().getName();
            item[4] = String.valueOf(data.getCompleteRate() == null ? 0 : data.getCompleteRate());
            item[5] = DateUtils.format(data.getStartTime(), DateUtils.FormatType.COMMON);
            item[6] = DateUtils.format(data.getEndTime(), DateUtils.FormatType.COMMON);
            item[7] = status;
            dataList.add(item);
        }
        POIUtils.exportExcel(resp, "课程学习情况", headers, dataList, "课程学习情况");

    }

    /**
     * 课程已培训人员列表
     */
    @GetMapping("personList")
    @RequirePermissions(values = "training:list")
    @Operation(summary = "课程已培训人员列表")
    public Response<Page<TrainingRefPersonDto>> personList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "课程id") @RequestParam Long trainingId
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getName))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getMobile));

        super.fillAuthorityData(request.getParams());
        int total = trainingPersonService.queryPersonTotal(request.getParams());

        List<TrainingRefPersonDto> list = null;
        if (total > 0) {
            list = trainingPersonService.queryPersonList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<TrainingRefPersonDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<TrainingRefPersonDto>>ok().wrap(page);
    }

    @GetMapping("queryAll")
    @RequirePermissions(values = "training:list")
    @Operation(summary = "条件查询列表")
    public Response<List<TrainingDto>> queryAll() {
        Map<String, Object> params = Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);
        List<TrainingDto> trainingDtos = trainingService.queryList(params);
        return Response.<List<TrainingDto>>ok().wrap(trainingDtos);
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "training:list")
    @Operation(summary = "分页列表")
    public Response<Page<TrainingDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(TrainingDto::getName));

        super.fillAuthorityData(request.getParams());
        int total = trainingService.queryTotal(request.getParams());

        List<TrainingDto> list = null;
        if (total > 0) {
            list = trainingService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<TrainingDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<TrainingDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "training:edit")
    @Operation(summary = "查询单条记录")
    public Response<TrainingDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingDto trainingDto = trainingService.selectById(id);

        // 反显人员信息
        Map<String, Object> queryPersonParams = new HashMap<>();
        queryPersonParams.put(LambdaUtil.getFieldName(TrainingPersonDto::getTrainingId), id);
        List<TrainingRefPersonDto> list = new ArrayList<>();
        int pageNo = 0;
        queryPersonParams.put("limit", 10000);
        while (true) {
            queryPersonParams.put("offset", pageNo++ * 10000);
            List<TrainingRefPersonDto> trainingCommentDtos = trainingPersonService.queryPersonList(queryPersonParams);
            if (CollectionUtils.isEmpty(trainingCommentDtos)) {
                break;
            }
            list.addAll(trainingCommentDtos);
        }
        List<PartyPersonDto> personDtos = CopyUtils.copyList(list, PartyPersonDto.class);
        Long[] personIds = personDtos.stream().map(PartyPersonDto::getId).toArray(Long[]::new);
        trainingDto.setPersons(personDtos);
        trainingDto.setPersonIds(personIds);
        return Response.<TrainingDto>ok().wrap(trainingDto);
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "training:info")
    @Operation(summary = "查询单条记录")
    public Response<TrainingDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingDto trainingDto = trainingService.selectById(id);

        return Response.<TrainingDto>ok().wrap((trainingDto));
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "training:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated TrainingDto trainingDto) {

        //填充基础数据
        fillSaveCommonData(trainingDto);

//        if (TrainingConstants.AssignMethodEnum.ALL.getAssignMethod().equals(trainingDto.getAssignMethod())) {
//            Map<String, Object> params = new HashMap<>();
//            params.put(LambdaUtil.getFieldName(PartyPersonDto::getPartyId), trainingDto.getPartyId());
//            super.fillAuthorityData(params);
//
//            List<PartyPersonDto> allPersonList = new ArrayList<>();
//            int pageNo = 0;
//            params.put("limit", 10000);
//            while (true) {
//                params.put("offset", pageNo++ * 10000);
//                List<PartyPersonDto> personDtos = partyPersonService.queryList(params);
//                if (CollectionUtils.isEmpty(personDtos)) {
//                    break;
//                }
//                allPersonList.addAll(personDtos);
//            }
//
//            Long[] allPersonIds = allPersonList.stream().map(PartyPersonDto::getId).toArray(Long[]::new);
//            trainingDto.setPersonIds(allPersonIds);
//        }

        trainingService.save(trainingDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "training:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated TrainingDto trainingDto) {
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(trainingDto.getId()));
        if (trainingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        long currentTimeMillis = System.currentTimeMillis();
        TrainingDto dbTrainingDto = trainingService.selectById(trainingDto.getId());
        if (TrainingConstants.PushStatusEnum.PUSHED.getPushStatus().equals(dbTrainingDto.getPushStatus())
                || currentTimeMillis > DateUtil.offsetMinute(dbTrainingDto.getStartTime(), -1 * (dbTrainingDto.getPushBeforeLearnMins() == null
                ? 0 : dbTrainingDto.getPushBeforeLearnMins())).getTime()) {

            // 已推送 或 当前时间大于推送时间
            return Response.error("仅未开始的课程允许编辑！");
        }

        //填充基础数据
        fillEditCommonData(trainingDto);

//        if (TrainingConstants.AssignMethodEnum.ALL.getAssignMethod().equals(trainingDto.getAssignMethod())) {
//            Map<String, Object> queryPersonParams = new HashMap<>();
//            queryPersonParams.put(LambdaUtil.getFieldName(PartyPersonDto::getPartyId), trainingDto.getPartyId());
//            super.fillAuthorityData(queryPersonParams);
//
//            List<PartyPersonDto> allPersonList = new ArrayList<>();
//            int pageNo = 0;
//            queryPersonParams.put("limit", 10000);
//            while (true) {
//                queryPersonParams.put("offset", pageNo++ * 10000);
//                List<PartyPersonDto> personDtos = partyPersonService.queryList(queryPersonParams);
//                if (CollectionUtils.isEmpty(personDtos)) {
//                    break;
//                }
//                allPersonList.addAll(personDtos);
//            }
//
//            Long[] allPersonIds = allPersonList.stream().map(PartyPersonDto::getId).toArray(Long[]::new);
//            trainingDto.setPersonIds(allPersonIds);
//        }

        trainingService.updateById(trainingDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "training:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        long currentTimeMillis = System.currentTimeMillis();

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (trainingService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }

            TrainingDto dbTrainingDto = trainingService.selectById(id);
            if (TrainingConstants.PushStatusEnum.PUSHED.getPushStatus().equals(dbTrainingDto.getPushStatus())
                    || currentTimeMillis > DateUtil.offsetMinute(dbTrainingDto.getStartTime(), -1 * (dbTrainingDto.getPushBeforeLearnMins() == null
                    ? 0 : dbTrainingDto.getPushBeforeLearnMins())).getTime()) {
                // 已推送 或 当前时间大于推送时间
                return Response.error("仅未开始的课程允许删除！");
            }
        }

        trainingService.deleteBatch(ids);

        return Response.ok();
    }
}
